const logger = require('log4js').getLogger()
const ObjectID = require('mongodb').ObjectID

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        if (!reqObj.name) {
            logger.error('[' + __filename + ':' + __line + ']', 'lack name')
            resolve({
                result: -1,
                msg: 'lack name'
            })
            return
        }
        if (!reqObj.startTime) {
            logger.error('[' + __filename + ':' + __line + ']', 'lack startTime')
            resolve({
                result: -1,
                msg: 'lack startTime'
            })
            return
        }
        if (!reqObj.endTime) {
            logger.error('[' + __filename + ':' + __line + ']', 'lack endTime')
            resolve({
                result: -1,
                msg: 'lack endTime'
            })
            return
        }
        if (!reqObj.num) {
            logger.error('[' + __filename + ':' + __line + ']', 'lack num')
            resolve({
                result: -1,
                msg: 'lack num'
            })
            return
        }
        if (!reqObj.money) {
            logger.error('[' + __filename + ':' + __line + ']', 'lack money')
            resolve({
                result: -1,
                msg: 'lack money'
            })
            return
        }
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            logger.error('[' + __filename + ':' + __line + ']', '未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return
        }
        new Promise((resolve, reject) => {
            if (reqObj.activityId) {
                mongoMng.db.collection('activity').find({
                    _id: ObjectID(reqObj.activityId)
                }).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        reject('system error')
                        return
                    }
                    if (result.length == 0) {
                        reject('system error')
                        return
                    }
                    var customer_phone_list = []
                    if (result[0].customers) {
                        var customers = result[0].customers
                        customers.forEach(item => {
                            customer_phone_list.push(item.customer_phone)
                        })
                    }
                    resolve(customer_phone_list)
                    mongoMng.db.collection('activity').updateOne({
                        _id: ObjectID(reqObj.activityId)
                    }, {
                        $set: {
                            name: reqObj.name,
                            startTime: reqObj.startTime,
                            endTime: reqObj.endTime,
                            num: reqObj.num,
                            money: reqObj.money
                        }
                    })
                })
            } else {
                mongoMng.db.collection('activity').insertOne({
                    name: reqObj.name,
                    startTime: reqObj.startTime,
                    endTime: reqObj.endTime,
                    num: reqObj.num,
                    money: reqObj.money
                }).then(result => {
                    reqObj.activityId = result.ops[0]._id
                    resolve([])
                }, result => {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    reject('system error')
                })
            }
        }).then(result => {
            mongoMng.db.collection('bill').aggregate([{
                $match: {
                    customer_phone: {
                        $nin: result,
                        $ne: null
                    },
                    $or: [{
                        taobaoTradeParentId: {
                            $ne: null
                        },
                        createTime: {
                            $gte: reqObj.startTime,
                            $lte: reqObj.endTime
                        }
                    }, {
                        orderId: {
                            $ne: null
                        },
                        orderDate: {
                            $gte: reqObj.startTime,
                            $lte: reqObj.endTime
                        }
                    }, {
                        orderId: {
                            $ne: null
                        },
                        orderTimeStr: {
                            $gte: reqObj.startTime,
                            $lte: reqObj.endTime
                        }
                    }, {
                        orderId: {
                            $ne: null
                        },
                        orderTime: {
                            $gte: new Date(reqObj.startTime).getTime(),
                            $lt: new Date(reqObj.endTime).getTime() + 1000
                        }
                    }, {
                        tradeParentId: {
                            $ne: null
                        },
                        tkCreateTime: {
                            $gte: reqObj.startTime,
                            $lte: reqObj.endTime
                        }
                    }]
                }
            }, {
                $group: {
                    _id: '$customer_phone',
                    num: {
                        $sum: 1
                    }
                }
            }]).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve({
                        result: -1,
                        msg: 'system error'
                    })
                    return
                }
                for (var i = 0; i < reqObj.num; ++i) {
                    var totalNum = 0
                    result.forEach(item => {
                        totalNum += item.num
                    })
                    var picked = Math.random() * totalNum
                    for (var j = 0; j < result.length; ++j) {
                        picked -= result[j].num
                        if (picked <= 0) {
                            let customer_phone = result[j]._id
                            mongoMng.db.collection('user').find({
                                phone: customer_phone
                            }).toArray((err, result) => {
                                if (err) {
                                    logger.error('[' + __filename + ':' + __line + ']', err)
                                    resolve({
                                        result: -1,
                                        msg: 'system error'
                                    })
                                    return
                                }
                                if (result.length > 0 && result[0].wechat) {
                                    let parm = {
                                        act_name: reqObj.name,
                                        client_ip: '123.56.115.107',
                                        mch_billno: require('../task/handleBillTask').getWechatBillno(),
                                        mch_id: '1510410651',
                                        nonce_str: require('../util/randomString')(32),
                                        re_openid: result[0].wechat,
                                        remark: reqObj.name,
                                        send_name: '旅悠省钱购',
                                        total_amount: reqObj.money * 100,
                                        total_num: 1,
                                        wishing: reqObj.name,
                                        wxappid: 'wx226c3c9557c44304',
                                    }
                                    require('../task/handleBillTask').sendWechatRedPack(parm).then(result => {
                                        mongoMng.db.collection('activity').updateOne({
                                            _id: ObjectID(reqObj.activityId)
                                        }, {
                                            $push: {
                                                customers: {
                                                    customer_phone: customer_phone,
                                                    money: reqObj.money,
                                                    send_time: require('../../lib/formatDate')(new Date())
                                                }
                                            }
                                        })
                                    }, result => {
                                        logger.error('[' + __filename + ':' + __line + ']', result)
                                    })
                                }
                            })
                            
                            result.splice(j, 1)
                            break
                        }
                    }
                }

                resolve({
                    result: 1
                })
            })
        }, result => {
            resolve({
                result: -1,
                msg: result
            })
        })
    })
}